import { Toast, List, InputItem, WhiteSpace, Picker } from 'antd-mobile';
import { Setting } from './Setting';

class RegionPicker extends React.Component {

  constructor(props) {
      super(props);

      let val = [];

      if (props.value) {
        let k = 0;
        while (k < props.value.length) {
          val.push(props.value.substr(k, 2));
          k += 2;
        }
      }

      this.state = {
        data: [],
        cols: 1,
        value: val,
      };

      // console.log(this.state);

      this.levels = [{
        code: 'SSDM', name: 'SSMC'
      }, {
        code: 'DJSDM', name: 'DJSMC'
      }, {
        code: 'XJSDM', name: 'XJSMC'
      }];
  }

  componentDidMount() {
    // console.log("Fetch " + Setting.BaseUrl + 'area/tree/' + this.state.value.join(""));

    fetch( Setting.BaseUrl + 'area/tree/' + (this.state.value.join("") || "00"), {
      credentials: 'include',
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(resp => resp.json()).then(json => {
      this.setState({data: json, cols: 1, value: this.state.value});
    });
  }

  findData(v, i, data) {
    let index = data.findIndex(x => x.value === v[i]);

    if (index >= 0) {
      return i < v.length - 1 ? this.findData(v, i + 1, data[index].children) : data[index];
    } else {
      return null;
    }
  }

  fetchData(val) {
    let data = this.state.data.slice(), item = this.findData(val, 0, data);

    if (val.length >= 3) {

      this.setState({data: data, cols: val.length, value: val});

    } else if (item && ! item.children) {
      fetch( Setting.BaseUrl + 'area/' + val.join("/"), {
        credentials: 'include',
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(resp => resp.json()).then(json => {
        let level = this.levels[val.length];

        item.children = json.result.map(x => {
          return {label: x[level.name], value: x[level.code]};
        });

        this.setState({data: data, cols: val.length + 1, value: val});
      });
    } else if (! item) {
      console.log("oops: can NOT find " + val.join("/"));
    } else {
    }
  }

  render() {
    return (
      <Picker 
        onPickerChange= {(val) => this.fetchData(val)} 
        extra= "请选择" 
        data= {this.state.data} 
        title= "选择地区" 
        cols= {this.state.cols}
        value= {this.state.value}
        onChange = { v => this.props.onChange && this.props.onChange(v.join("")) }
      >
      <List.Item arrow="horizontal">{this.props.title}</List.Item>
      </Picker>
    );
  }
}

export default RegionPicker;
